#include "audioplayer.h"
#include <QDir>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QDebug>
static const QString s_curDir = QDir::currentPath() + "/";    //绝对路径

AudioPlayer::AudioPlayer(QObject *parent) :QObject(parent),backgroundMusic(NULL)
{
    QUrl backgroundMusicUrl = QUrl::fromLocalFile("music/BGM.mp3");
    qDebug()<<s_curDir+"music/BGM.mp3";
    player=new QMediaPlayer(this);
    if(QFile::exists(backgroundMusicUrl.toLocalFile()))
    {
        backgroundMusic = new QMediaPlayer(this);
        QMediaPlaylist *backgroundMusicList = new QMediaPlaylist();

        QMediaContent media(backgroundMusicUrl);
        backgroundMusicList->addMedia(media);
        backgroundMusicList->setCurrentIndex(0);
        backgroundMusicList->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);    //循环播放
        backgroundMusic->setPlaylist(backgroundMusicList);
    }
    //musicUrl[0]=QUrl::fromLocalFile("music/click.wav");

}

void AudioPlayer::startBGM()
{
    if(backgroundMusic)
    {
        qDebug()<<"playBGM";
        qDebug()<<"Url:"<<musicUrl[0];
        backgroundMusic->play();

    }
}

void AudioPlayer::setMuted(bool checked)
{
    if(checked)backgroundMusic->setMuted(true);
    else backgroundMusic->setMuted(false);
}

void AudioPlayer::setBgmValue(int value)
{
    backgroundMusic->setVolume(value);
}

int AudioPlayer::getBgmValue()
{
    return backgroundMusic->volume();
}

void AudioPlayer::playSound(int id)
{
    qDebug()<<"Url:"<<musicUrl[0];
    if(QFile::exists(musicUrl[id].toLocalFile()))
    {
        qDebug()<<"succeed";
        player->setMedia(musicUrl[id]);
        player->play();
    }
}
